package com.ruoyi.app.common.jwt;


import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.system.domain.app.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     *
     *
     * @return 结果
     */
    public String login(String username, String password,String appId)
    {
        redisCache.setCacheObject(username,appId);
        // 用户验证
        Authentication authentication = null;
        // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
        authentication = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(username+":"+appId, password));
//        try
//        {
//
//        }
//        catch (Exception e)
//        {
////            if (e instanceof BadCredentialsException)
////            {
////                throw new UserPasswordNotMatchException();
////            }
////            else
////            {
////                throw new CustomException(e.getMessage());
////            }
//        }
        User loginUser = (User) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }
}
